#include "common.h"
#include "button.h"

void init_button(button* b, char* text, int x, int y, int w, int h, int toggle)
{
	b->rect.x = x;
	b->rect.y = (y+(h/2))-30;
	b->rect.h = h; 
	b->rect.w = w;

	// setup text surface
	TTF_Font* font = TTF_OpenFont("/usr/share/fonts/arial.ttf", 16);
	SDL_Color color = {0xFF,0xFF,0xFF};
	b->text = TTF_RenderText_Solid(font, text, color);
	TTF_CloseFont(font);

	b->toggle_type = toggle;
	b->toggled = 0;
}

int touch_button(button* b, int x, int y)
{
	int inside = INSIDE_RECT(b->rect, x, y);
	if (inside)
	{
		if (b->toggle_type)
			b->toggled = !b->toggled;
		else
			b->toggled = 1;
	}
	else
	{
		if (!b->toggle_type)
			b->toggled = 0;
	}
	return inside;
}

void free_button(button* s)
{
	//SDL_FreeSurface(s->img); 
}

void display_button(SDL_Surface* screen, button* b)
{
	SDL_Rect text_offset;
	text_offset.x = b->rect.x + (0.5*(b->rect.w-b->text->w));
	text_offset.y = b->rect.y + (0.5*(b->rect.h-b->text->h));

	Uint8 red,green,blue;
	if (b->toggle_type)
	{
		if (b->toggled)
		{
			red = 0; green = 0xFF; blue = 0;
		}
		else
		{
			red = 0xFF; green = 0; blue = 0;
		}
	}
	else
	{
		if (b->toggled)
		{
			red = 0; green = 0; blue = 0x44;
		}
		else
		{
			red = 0xAA; green = 0xAA; blue = 0xAA;
		}
	}
	SDL_FillRect(screen, &b->rect, SDL_MapRGB(screen->format, red, green, blue));
	SDL_BlitSurface(b->text, NULL, screen, &text_offset);
}

int get_button_toggled(button* b)
{
	return b->toggled;
}

int set_button_toggled(button* b, int toggled)
{
	b->toggled = toggled;
}
